package module

import (
	"github.com/natefinch/lumberjack"
	"github.com/sirupsen/logrus"
	"github.com/topfreegames/pitaya"
	"github.com/topfreegames/pitaya/logger"
	"github.com/topfreegames/pitaya/modules"
	"pitaya_new_chatroom/hooks"
	"pitaya_new_chatroom/manager/global"
)

type LoggerRotate struct{
	Path string
	MaxSize int
	MaxBackups int
	MaxAge int
	Compress bool
	Source string
	modules.Base

}


func NewLoggerRotate() *LoggerRotate{
	config := pitaya.GetConfig()
	return &LoggerRotate{
		Path:config.GetString("chatroom.loggerRotate.path"),
		MaxSize:config.GetInt("chatroom.loggerRotate.maxsize"),
		MaxBackups:config.GetInt("chatroom.loggerRotate.maxbackups"),
		MaxAge:config.GetInt("chatroom.loggerRotate.maxage"),
		Compress:config.GetBool("chatroom.loggerRotate.compress"),
		Source:config.GetString("chatroom.loggerRotate.source"),
	}
}

func (log *LoggerRotate) Init() error{


	if pitaya.GetConfig().GetString("chatroom.env") != "development"{
		l:= &lumberjack.Logger{
			Filename: log.Path,
			MaxSize: log.MaxSize,
			MaxBackups: log.MaxBackups,
			MaxAge:     log.MaxAge,
			Compress:log.Compress,

		}

		rlog:=logrus.New()
		rlog.Formatter = new(logrus.JSONFormatter)
		rlog.Level = logrus.InfoLevel
		rlog.SetOutput(l)
		newLog:=rlog.WithFields(logrus.Fields{
			"source":log.Source,
		})
		emailConfig:=pitaya.GetConfig().Get("email")
		email:= emailConfig.(map[string]interface{})

		receiver:=email["to"].([]interface{})
		receiverStrs:= make([]string,len(receiver))
		if len(receiver) >0{
			for idx,val:=range receiver{
				receiverStrs[idx] =val.(string)
			}
		}

		hook,_:= hooks.NewMailAuthHook(
			pitaya.GetServer().Type,
			email["host"].(string),
			int(email["port"].(float64)),
			email["from"].(string),
			receiverStrs,
			email["username"].(string),
			email["password"].(string),
			[]logrus.Level{logrus.ErrorLevel,logrus.FatalLevel,logrus.PanicLevel},
		)

		rlog.AddHook(hook)
		// 和logger.Log 区分开 不是所有的Error消息都需要发邮件，按需发就好
		global.G.Log = newLog
	}else {

		logger.Log.Debugln("测试环境日志打进控制台，方便调试！！")
	}


	return nil
}